<?php

class MTaskRecordItem extends MY_Model
{

    protected $table = 'task_record_item';
    private $filter = array();

    function __construct()
    {
        parent::__construct();
    }

    //0:初始待提交财务，1，财务待处理，2，财务标定异常，3，财务已处理打款
    public static function getState($state = NULL)
    {
        $define = array(
            '0' => '<span class="label label-primary">初始待提交财务</span>',
            '1' => '<span class="label label-warning">财务待处理</span>',
            '2' => '<span class="label label-danger">财务标定异常</span>',
            '3' => '<span class="label label-success">财务已处理打款</span>');
        if ($state === NULL) {
            return $define;
        } else {
            return key_exists($state, $define) ? $define[$state] : '';
        }
    }

    /**
     * 修改给定payrequestid的状态为给定的status
     * @param $pay_request_id
     */
    public function updateAllOperateStatusByPayRequestID($pay_request_id, $finance_id, $status)
    {
        $sql = "update `core_task_operate` set status=" . (int)$status . ", finance_id = " . $finance_id . " where `pay_request_id`=" . (int)$pay_request_id;
        return $this->db->query($sql);
    }


    /**
     * 修改给定payrequestid的状态状态为财务 3的为财务待处理 已处理5
     */
    public function updateAllOperateStatus3To5ByPayRequestID($pay_request_id, $finance_id)
    {
        $sql = "update `core_task_operate` set status=5, finance_id = " . $finance_id . " where status = 3 AND `pay_request_id`=" . (int)$pay_request_id;
        return $this->db->query($sql);
    }

    public function updateAllItemStatusByPayRequestID($pay_request_id, $finance_id)
    {
        $sql = "update `core_task_record_item` set status=3, finance_id = " . $finance_id . " where status = 1 AND `pay_request_id`=" . (int)$pay_request_id;
        return $this->db->query($sql);
    }

    public function getList($limit, $ids = null, $sort = false)
    {
        $this->db->select(
            'item.id,item.record_id,item.pay_method,item.status,item.payment_type,item.create_time,item.update_time,item.amount,item.coin_type,item.contact,item.pay_account,item.rate_rmb,t.id task_id, t.product_name,t.asin,t.shop_id,t.creator_id,t.image,t.country,t.group_id,record.order_no, record.operator_id, record.ceping_type,record.buyer_pay_total,record.buyer_pay_coin_type');
        $this->db->distinct();
        $this->db->from($this->table . ' item');
        $this->db->join('task_records record', 'item.record_id = record.id', 'LEFT');
        $this->db->join('task t', 'record.task_id = t.id', 'LEFT');
        $this->db->limit($limit['limit'], $limit['offset']);
        $this->formfilter->doFilter();
        if ($ids) {
            $this->db->where('item.id in (' . $ids . ')');
        }
        if (in_array($this->_user->role_id, array(2, 3, 4, 5))) {   //测评组员或组长，只能看自己的
            $this->db->where('record.operator_id', $this->_user->id);
        }
        $this->db->order_by('item.id', 'desc');
        $query = $this->db->get();
        return $query->result();
    }

    public function getCount($ids = false)
    {
        $this->db->select('count(distinct item.id) as num');
        $this->db->from($this->table . ' as item');
        $this->db->join('task_records record', 'item.record_id = record.id', 'LEFT');
        $this->db->join('task t', 'record.task_id = t.id', 'LEFT');
        $this->formfilter->doFilter();
        if ($ids) {
            $this->db->where('item.id in (' . $ids . ')');
        }
        if (in_array($this->_user->role_id, array(2, 3, 4, 5))) {   //测评组员或组长，只能看自己的
            $this->db->where('record.operator_id', $this->_user->id);
        }
        $tmp = $this->db->get()->result();
        return (int)$tmp[0]->num;
    }

    public function getFinanceList($apply_id, $sort = false) {
        $this->db->select(
            'item.id,item.record_id,item.amount,item.coin_type,item.pay_method,item.status,item.payment_type,item.create_time,item.update_time ,
                    t.id task_id, t.product_name,t.asin,t.shop_id,t.creator_id,t.image,t.country,t.group_id,
                    record.order_no, record.operator_id, record.ceping_type,record.buyer_pay_total,record.buyer_pay_coin_type'
        );
        $this->db->distinct();
        $this->db->from($this->table . ' item');
        $this->db->join('task_records record', 'item.record_id = record.id', 'LEFT');
        $this->db->join('task t', 'record.task_id = t.id', 'LEFT');
        $this->db->where('item.pay_request_id',$apply_id);

        $this->db->order_by('item.id', 'desc');

        $query = $this->db->get();
        return $query->result();
    }

    public function getFinanceCount($apply_id)
    {
        $this->db->select('count(distinct item.id) as num');
        $this->db->from($this->table . ' item');
        $this->db->join('task_records record', 'item.record_id = record.id', 'LEFT');
        $this->db->join('task t', 'record.task_id = t.id', 'LEFT');
        $this->db->where('item.pay_request_id',$apply_id);
        $tmp = $this->db->get()->result();
        return (int)$tmp[0]->num;
    }

    public function getById($id){
        $query = $this->db->where('id', $id)->get($this->table);
        return $query->row();
    }

    public function getAllByCepingId($ids)
    {
        $ids_str = '(' . implode(',', $ids) . ')';
        $this->db->select('payment_type,status');
        $this->db->from($this->table);
        $this->db->where('id in ' . $ids_str);
        $query = $this->db->get();
        $queryResult = $query->result();
        $kvArr = array();
        foreach ($queryResult as $k => $v) {
            $kvArr['payment_types'][] = $v->payment_type;
            $kvArr['statuses'][] = $v->status;
        }
        return $kvArr;
    }

    public function getAllByCepingIdDel($ids)
    {
        $ids_str = '(' . implode(',', $ids) . ')';
        $this->db->select('id,record_id,update_time');
        $this->db->from($this->table);
        $this->db->where('id in ' . $ids_str);
        $query = $this->db->get();

        return $query->result();
    }

    public function getAllFinanceOperate($ids)
    {
        $this->db->select('op.*,t.product_name,t.asin,t.shop_id,t.creator_id,t.image,t.country,t.group_id,t.price');
        $this->db->distinct();
        $this->db->from($this->table . ' op');
        $this->db->join('admins a1', 'op.operator_id = a1.id', 'LEFT');
        $this->db->join('task t', 'op.task_id = t.id', 'LEFT');
        $this->db->join('shops sp', 'sp.id = t.shop_id', 'LEFT');
        $this->formfilter->doFilter();
        if ($ids) {
            $this->db->where('op.id in (' . $ids . ')');
        }
        $query = $this->db->get();
        return $query->result();
    }

    public function getDistinctOrderNoOperates($task_id, $operator_id)
    {
        $this->db->select('count(distinct(order_no)) as operate_numbers');
        $this->db->from($this->table);
        $this->db->where(['task_id' => $task_id, 'operator_id' => $operator_id]);
        return $this->db->get()->row();
    }

    public function getCountNum($begintime, $endtime, $line_type, $allReviews, $apply)
    {

        $this->db->select('op.id,op.operator_id,op.create_time,a.name,a.account');
        $this->db->from($this->table . ' op');
        $this->db->join('admins a', 'op.operator_id = a.id', 'LEFT');

        if ($apply == 'init') {
            $x = $this->get_weeks();
            $this->db->where('op.create_time >= ',strtotime($x[0] . ' 00:00:00'));
            $this->db->where('op.create_time <= ',strtotime($x[6] . ' 23:59:59'));
        } else {
            $x = $this::getDateFromRange($begintime, $endtime, $line_type);
            if ($begintime) {
                $this->db->where('op.create_time >= ',strtotime($begintime . ' 00:00:00'));
            }
            if ($endtime) {
                $this->db->where('op.create_time <= ',strtotime($endtime . ' 23:59:59'));
            }
        }

        if ($apply == 'init') {
            $x = $this::get_weeks();
        } else {
            $x = $this::getDateFromRange($begintime, $endtime, $line_type);
        }
        $list = $this->db->get()->result();

        //更改日期格式timestamp
        if ($line_type == 2) {
            $format = 'Y-m';
        } else if ($line_type == 3) {
            $format = 'Y-m-d';
        } else if ($line_type == 1) {
            $format = 'Y';
        } else {
            $format = 'Y-m-d';
        }

        if (count($list)){
            foreach ($list as $value) {
                $value->create_time = date($format, $value->create_time);
                $item[] = $value;
            };

            $new[0] = array_merge(['taskOperate'],$x);
            foreach ($allReviews as $r_k => $r_v) {
                $op_user_arr = [];
                array_unshift($op_user_arr,$r_v);
                foreach ($x as $x_v) {
                    $op_user_arr[$x_v] = 0;
                    foreach ($item as $i_k => $i_v) {
                        if ($x_v == $i_v->create_time && $i_v->operator_id == $r_k) {
                            $op_user_arr[$x_v] += 1;
                        }
                    }
                }
                $new[] =  array_values($op_user_arr);
            }

            $source[0] = array_merge(['taskOperate'], $x);
            return $new;
        }else{
            $new[0] = array_merge(['taskOperate'],$x);
            foreach ($allReviews as $r_k => $r_v) {
                $op_user_arr = [];
                array_unshift($op_user_arr,$r_v);
                foreach ($x as $x_v) {
                    $op_user_arr[$x_v] = 0;
                }
                $new[] =  array_values($op_user_arr);
            }

            $source[0] = array_merge(['taskOperate'], $x);
            return $new;
        }
    }


    public function getAll($where=null,$order_by=null){
        $this->db->select("*");
        $this->db->from($this->table);
        if($where != null){
            foreach ($where as $k => $v){
                if ($k == 'payment_type'){
                    $this->db->where_in('payment_type',$v);
                }else{
                    $this->db->where($k,$v);
                }
            }
        }
        if($order_by != null){
            $this->db->order_by($order_by);
        }
        return $this->db->get()->result();
    }

    /**
     * @param array
     * @return object
     * excel 表格导出查询数据
     */
    public function exportList($where)
    {
        $this->db->select('item.*,a2.name,
        record.order_no, record.operator_id,record.add_image,record.add_image_1,record.add_image_2, record.ceping_type,record.buyer_pay_total,record.buyer_pay_coin_type,record.buyer_pay_time,buyer_order_time,record.comment_link,record.true_product_price,
        t.id as task_id,t.product_name,t.image as product_image,t.asin,t.shop_id,sp.name as shop_name,a1.name as operator_name');
        $this->db->distinct();
        $this->db->from($this->table . ' item');
        $this->db->join('task_records record', 'item.record_id = record.id', 'LEFT');
        $this->db->join('task t', 'record.task_id = t.id', 'LEFT');
        $this->db->join('shops sp', 't.shop_id = sp.id', 'LEFT');
        $this->db->join('admins a1', 'record.operator_id = a1.id', 'LEFT');
        $this->db->join('admins a2', 'item.finance_id = a2.id', 'LEFT');

        if ($begintime = $where['task_record_item_create_time_begin']) {
            $this->db->where(array('item.create_time >= ' => strtotime($begintime . ' 00:00:00')));
        }

        if ($endtime = $where['task_record_item_create_time_end']) {
            $this->db->where(array('item.create_time <= ' => strtotime($endtime . ' 23:59:59')));
        }

        if ($begintime = $where['task_record_item_update_time_begin']) {
            $this->db->where(array('item.update_time >= ' => strtotime($begintime . ' 00:00:00')));
        }

        if ($endtime = $where['task_record_item_update_time_end']) {
            $this->db->where(array('item.update_time <= ' => strtotime($endtime . ' 23:59:59')));
        }

        if ($where['task_id']) {
            $this->db->where('record.task_id', $where['task_id']);
        }
        if ($where['payment_type']) {
            $this->db->where('item.payment_type', $where['payment_type']);
        }
        if ($where['pay_method']) {
            $this->db->where('item.pay_method', $where['pay_method']);
        }
        if ($where['order_no']) {
            $this->db->where('record.order_no', $where['order_no']);
        }
        if ($where['operator_id']) {
            $this->db->where('record.operator_id', $where['operator_id']);
        }
        if ($where['status']) {
            $this->db->where('item.status', $where['status']);
        }
        if ($where['group_id']) {
            $this->db->where('t.group_id', $where['group_id']);
        }
        if ($where['shop_id']) {
            $this->db->where('sp.shop_id', $where['shop_id']);
        }

        if (in_array($this->_user->role_id, [2, 3, 4, 5])) {   //测评组的人，只能看到自己
            $this->db->where('record.operator_id', $this->_user->id);
        }

        $result = $this->db->get()->result();

        foreach ($result as $k => $v) {
            $v->shop_id = $v->shop_name;
            $v->buyer_pay_coin_type = IOSS_StaticConfig::getcoinTypeInfo($v->buyer_pay_coin_type);
            $v->coin_type = IOSS_StaticConfig::getcoinTypeInfo($v->coin_type);
            $v->operator_id = $v->operator_name;
            $v->pay_method = IOSS_StaticConfig::getPayMethod($v->pay_method);
            $v->payment_type = IOSS_StaticConfig::getPayTypeInfo($v->payment_type);
            $v->buyer_pay_total = number_format($v->buyer_pay_total, 2, '.', '');
            $v->task_id = $v->product_name;
            $v->finance_id = $v->name;
            $v->status = strip_tags($this->getState($v->status));
            $v->create_time = $v->create_time ? date('Y-m-d H:i:s', $v->create_time) : '';
            $v->update_time = $v->update_time ? date('Y-m-d H:i:s', $v->update_time) : '';
            $v->buyer_order_time = $v->buyer_order_time ? date('Y-m-d', $v->buyer_order_time) : '';
            $v->buyer_pay_time = $v->buyer_pay_time ? date('Y-m-d', $v->buyer_pay_time) : '';
        }
        return $result;
    }

    public function exportPayList($pay_request_id)
    {
        $this->db->select('item.*,a2.name,
        record.order_no, record.operator_id,record.add_image,record.add_image_1,record.add_image_2, record.ceping_type,record.buyer_pay_total,record.buyer_pay_coin_type,record.buyer_pay_time,buyer_order_time,record.comment_link,record.true_product_price,
        t.id as task_id,t.product_name,t.image as product_image,t.asin,t.shop_id,sp.name as shop_name,a1.name as operator_name,ag.name as admin_group_name');
        $this->db->distinct();
        $this->db->from($this->table . ' item');
        $this->db->join('task_records record', 'item.record_id = record.id', 'LEFT');
        $this->db->join('task t', 'record.task_id = t.id', 'LEFT');
        $this->db->join('shops sp', 't.shop_id = sp.id', 'LEFT');
        $this->db->join('admins a1', 'record.operator_id = a1.id', 'LEFT');
        $this->db->join('admins a2', 'item.finance_id = a2.id', 'LEFT');
        //==================liuwei added===========
        $this->db->join('admin_group ag', 'a1.group_id = ag.id', 'LEFT');
        $this->db->where('item.pay_request_id', $pay_request_id);
        $this->db->order_by('id', 'asc');
        $result = $this->db->get()->result();

        foreach ($result as $k => $v) {
            $v->shop_id = $v->shop_name;
            $v->buyer_pay_coin_type = IOSS_StaticConfig::getcoinTypeInfo($v->buyer_pay_coin_type);
            $v->coin_type = IOSS_StaticConfig::getcoinTypeInfo($v->coin_type);
            $v->operator_id = $v->operator_name;
            $v->pay_method = IOSS_StaticConfig::getPayMethod($v->pay_method);
            $v->payment_type = IOSS_StaticConfig::getPayTypeInfo($v->payment_type);
            $v->buyer_pay_total = number_format($v->buyer_pay_total, 2, '.', '');
            $v->task_id = $v->product_name;
            $v->finance_id = $v->name;
            $v->status = strip_tags($this->getState($v->status));
            $v->create_time = $v->create_time ? date('Y-m-d H:i:s', $v->create_time) : '';
            $v->update_time = $v->update_time ? date('Y-m-d H:i:s', $v->update_time) : '';
            $v->buyer_order_time = $v->buyer_order_time ? date('Y-m-d', $v->buyer_order_time) : '';
            $v->buyer_pay_time = $v->buyer_pay_time ? date('Y-m-d', $v->buyer_pay_time) : '';
        }
        return $result;
    }

    public function getListByIds($ids){
        $this->db->select('item.*,a2.name,
        record.order_no, record.operator_id,record.add_image,record.add_image_1,record.add_image_2, record.ceping_type,record.buyer_pay_total,record.buyer_pay_coin_type,record.buyer_pay_time,buyer_order_time,record.comment_link,record.true_product_price,
        t.id as task_id,t.product_name,t.image as product_image,t.asin,t.shop_id,sp.name as shop_name,a1.name as operator_name');
        $this->db->distinct();
        $this->db->from($this->table . ' item');
        $this->db->join('task_records record', 'item.record_id = record.id', 'LEFT');
        $this->db->join('task t', 'record.task_id = t.id', 'LEFT');
        $this->db->join('shops sp', 't.shop_id = sp.id', 'LEFT');
        $this->db->join('admins a1', 'record.operator_id = a1.id', 'LEFT');
        $this->db->join('admins a2', 'item.finance_id = a2.id', 'LEFT');
        $ids_str = '(' . implode(',', $ids) . ')';
        $this->db->where('item.id in ' . $ids_str);
        $result = $this->db->get()->result();

        foreach ($result as $k => $v) {
            $v->shop_id = $v->shop_name;
            $v->buyer_pay_coin_type = IOSS_StaticConfig::getcoinTypeInfo($v->buyer_pay_coin_type);
            $v->coin_type = IOSS_StaticConfig::getcoinTypeInfo($v->coin_type);
            $v->operator_id = $v->operator_name;
            $v->pay_method = IOSS_StaticConfig::getPayMethod($v->pay_method);
            $v->payment_type = IOSS_StaticConfig::getPayTypeInfo($v->payment_type);
            $v->buyer_pay_total = number_format($v->buyer_pay_total, 2, '.', '');
            $v->task_id = $v->product_name;
            $v->finance_id = $v->name;
            $v->status = strip_tags($this->getState($v->status));
            $v->create_time = $v->create_time ? date('Y-m-d H:i:s', $v->create_time) : '';
            $v->update_time = $v->update_time ? date('Y-m-d H:i:s', $v->update_time) : '';
            $v->buyer_order_time = $v->buyer_order_time ? date('Y-m-d', $v->buyer_order_time) : '';
            $v->buyer_pay_time = $v->buyer_pay_time ? date('Y-m-d', $v->buyer_pay_time) : '';
        }
        return $result;
    }

    public function getListByRequestIds($request_ids)
    {
        $this->db->select('item.*,a2.name,
        record.order_no, record.operator_id,record.add_image,record.add_image_1,record.add_image_2, record.ceping_type,record.buyer_pay_total,record.buyer_pay_coin_type,record.buyer_pay_time,buyer_order_time,record.comment_link,record.true_product_price,
        t.id as task_id,t.product_name,t.image as product_image,t.asin,t.shop_id,sp.name as shop_name,a1.name as operator_name,ag.name as admin_group_name');
        $this->db->distinct();
        $this->db->from($this->table . ' item');
        $this->db->join('task_records record', 'item.record_id = record.id', 'LEFT');
        $this->db->join('task t', 'record.task_id = t.id', 'LEFT');
        $this->db->join('shops sp', 't.shop_id = sp.id', 'LEFT');
        $this->db->join('admins a1', 'record.operator_id = a1.id', 'LEFT');
        $this->db->join('admins a2', 'item.finance_id = a2.id', 'LEFT');
        //=========liuwei added===================
        $this->db->join('admin_group ag','a1.group_id=ag.id','LEFT');

        $ids_str = '(' . $request_ids . ')';
        $this->db->where('item.pay_request_id in ' . $ids_str);

        $result = $this->db->get()->result();

        foreach ($result as $k => $v) {
            $v->shop_id = $v->shop_name;
            $v->buyer_pay_coin_type = IOSS_StaticConfig::getcoinTypeInfo($v->buyer_pay_coin_type);
            $v->coin_type = IOSS_StaticConfig::getcoinTypeInfo($v->coin_type);
            $v->operator_id = $v->operator_name;
            $v->pay_method = IOSS_StaticConfig::getPayMethod($v->pay_method);
            $v->payment_type = IOSS_StaticConfig::getPayTypeInfo($v->payment_type);
            $v->buyer_pay_total = number_format($v->buyer_pay_total, 2, '.', '');
            $v->task_id = $v->product_name;
            $v->finance_id = $v->name;
            $v->status = strip_tags($this->getState($v->status));
            $v->create_time = $v->create_time ? date('Y-m-d H:i:s', $v->create_time) : '';
            $v->update_time = $v->update_time ? date('Y-m-d H:i:s', $v->update_time) : '';
            $v->buyer_order_time = $v->buyer_order_time ? date('Y-m-d', $v->buyer_order_time) : '';
            $v->buyer_pay_time = $v->buyer_pay_time ? date('Y-m-d', $v->buyer_pay_time) : '';
        }
        return $result;
    }

    public function getAllFee($month,$group_id,$shop_id){
        $this->db->select("i.amount,i.coin_type,t.asin");
        $this->db->from($this->table.' i');
        $this->db->where('i.status',3);
        $this->db->join('task_records r','r.id = i.record_id and FROM_UNIXTIME(r.buyer_order_time, \'%Y_%m\') = '."'".$month."'");
        if ($shop_id){
            $this->db->join('task t','r.task_id = t.id and t.shop_id = '.$shop_id);
        }else{
            $this->db->join('task t','r.task_id = t.id and t.group_id = '.$group_id);
        }

        return $this->db->get()->result();
    }
}
